import re
import cv2
import html2text
import requests
import numpy as np
import pypandoc
from bs4 import BeautifulSoup
from lxml import html


def html_save_docx(h1_title, body_content, image_folder="images",save_docx_folder="docx"):
    """
    将网页源码保存为docx
    :param h1_title:
    :param body_content:
    :param image_folder:
    :return:
    """

    def is_image(content, output_path):
        jpeg_magic_number = b"\xFF\xD8"
        png_magic_number = b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"
        gif_magic_number = b"\x47\x49\x46\x38"
        jpeg_magic_number_2 = b"RIFF"
        if content.startswith(png_magic_number):
            image = np.asarray(bytearray(content), dtype="uint8")
            image = cv2.imdecode(image, cv2.IMREAD_COLOR)
            cv2.imwrite(f'{output_path}.png', image)
            return f'{output_path}.png'
        elif content.startswith(jpeg_magic_number_2):
            image = np.asarray(bytearray(content), dtype="uint8")
            image = cv2.imdecode(image, cv2.IMREAD_COLOR)
            cv2.imwrite(f'{output_path}.jpg', image)
            return f'{output_path}.jpg'
        elif content.startswith(jpeg_magic_number):
            image = np.asarray(bytearray(content), dtype="uint8")
            image = cv2.imdecode(image, cv2.IMREAD_COLOR)
            cv2.imwrite(f'{output_path}.jpg', image)
            return f'{output_path}.jpg'
        elif content.startswith(gif_magic_number):
            with open(f'{output_path}.gif', 'wb') as f:
                # 写入获取到的内容
                f.write(content)
            return f'{output_path}.gif'
        else:
            return False

    def download_image(url, output_path):
        response = requests.get(url)  # 替换url为你要下载的URL
        file_type = is_image(response.content, output_path)
        return file_type

    def convert_markdown_images(text, image_folder):
        image_pattern = re.compile(r'!\[.*\]\((https.*?)\)')
        matches = image_pattern.findall(text)
        for mun, match in enumerate(matches):
            url = match
            # 下载图片并保存到本地
            new_url = download_image(url, f"{image_folder}/{mun}")
            # 替换图片URL为本地路径
            if new_url is False:
                continue
            text = text.replace(url, new_url)
        return text
    html_content = f"<html><head><meta charset='UTF-8'><title>{h1_title}</title></head><body><h1>{h1_title}</h1>{body_content}</body></html>"
    # 使用BeautifulSoup解析HTML内容

    markdown_content = html2text.html2text(html_content, bodywidth=0)
    converted_text = convert_markdown_images(markdown_content, image_folder)

    save_title = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9\s]', '', h1_title) + '.docx'
    save_title = save_title.replace('\n','').replace('\t','').replace(' ','')
    pypandoc.convert_text(converted_text, 'docx', format='markdown', outputfile=save_docx_folder+'/'+save_title)